<template>
  <div class="tab-bar">
    <template v-for="(item,index) in tabbarData" :key="index">
      <div class="tab-bar-item" :class="{active: currentIndex === index }" @click="itemClick(index,item)">
        <img :src="getAssetsFile(item.image)" alt="" v-if="currentIndex !== index">
        <img :src="getAssetsFile(item.imageActive)" alt="" v-else>
        <span class="text">{{ item.text }}</span>
      </div>

      <!-- 有两种方案，第一种是上面的通过watch找到index,第二种是直接通过路由来使用 -->

      <!-- <div class="tab-bar-item" :class="{active: route.path === item.path }" @click="itemClick(index,item)">
        <img :src="getAssetsFile(item.image)" alt="" v-if="route.path !== item.path">
        <img :src="getAssetsFile(item.imageActive)" alt="" v-else>
        <span class="text">{{ item.text }}</span>
      </div> -->
    </template>
  </div>
</template>

<script setup>
import { useRouter, useRoute } from 'vue-router'
import { ref, watch } from 'vue'
import tabbarData from '@/assets/data/tabbar.js'
import { getAssetsFile } from '@/utils/load_assets.js'

const router = useRouter()
const route = useRoute()
const currentIndex = ref(0)

watch(route,(newRoute) => {
  const index = tabbarData.findIndex(item => item.path === newRoute.path)
  if(index === -1) return
  currentIndex.value = index
})

const itemClick = (index, item) => {
  currentIndex.value = index
  router.push(item.path)
}
</script>

<style lang="less" scoped>
.tab-bar {
  position: fixed;
  height: 100px;
  bottom: 0;
  right: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  border-top: 2px solid #ddd;
  background-color: #fff;
  .tab-bar-item {
    display: flex;
    flex: 1;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    &.active {
      color: var(--primary-color);
    }

    img {
      width: 68px;
    }

    .text {
      font-size: 24px;
    }
  }
}
</style>